package com.jushu.storbox.callback;

import java.util.Comparator;

import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileType;
import com.jushu.storbox.util.DateUtil;

public class FileFolderInfoTimeSort implements Comparator<FileFolderInfo> {
	private int sortType;

	public FileFolderInfoTimeSort(int sortType) {
		this.sortType = sortType;
	}

	@Override
	public int compare(FileFolderInfo lhs, FileFolderInfo rhs) {
		long compareAscResult = 0;
		
		long lTime = DateUtil.getDayTime(lhs.getModifiedAt());
		long rTime = DateUtil.getDayTime(rhs.getModifiedAt());
		compareAscResult = lTime - rTime;
		if(compareAscResult == 0) {
			compareAscResult = compareFileFolderInfo(lhs,rhs);
			if(compareAscResult == 0) {
				compareAscResult = lhs.getModifiedAt() - rhs.getModifiedAt();
				return modifyResult(compareAscResult, true);
			}
			return modifyResult(compareAscResult, false);
		} else {
			return modifyResult(compareAscResult, true);
		}
	}
	
	private int modifyResult(long result, boolean modifyFlag) {
		long lResult = result;
		if(modifyFlag) {
			if(sortType == UiConstant.SORT_BY_TIME) {//升序排序
				lResult = result;
			} else {
				lResult =  (result * -1);
			}
		}
		
		if(lResult > 0) {
			return 1;
		} else if(lResult == 0) {
			return 0;
		} else {
			return -1;
		}
	}
	
	private int compareFileFolderInfo(FileFolderInfo lhs, FileFolderInfo rhs) {
		if (lhs.getIsFile() == FileType.FOLDER_TYPE_VALUE 
				&& rhs.getIsFile() == FileType.FILE_TYPE_VALUE) {
			return -1;
		} else if (lhs.getIsFile() == FileType.FILE_TYPE_VALUE 
				&& rhs.getIsFile() == FileType.FOLDER_TYPE_VALUE) {
			return 1;
		} else {
			return 0;
		}
	}

}
